package com.example.demo.auth.service;


import com.example.demo.entity.SysRequestPath;
import com.example.demo.service.SysRequestPathService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

//判断是否有权限（权限动态加载）
@Service("DynPermissionService")
public class DynPermissionService  {
    @Resource
    SysRequestPathService sysRequestPathService;

    //根据用户名判断用户是否有权限访问
    public Boolean checkPermission(HttpServletRequest request,
                                   Authentication authentication){
        Object principal = authentication.getPrincipal();

        //springSecurity自带工具类
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        //得到请求的访问路径
        String url = request.getRequestURI();

        if(principal instanceof UserDetails){
            UserDetails userDetails = (UserDetails) principal;
            //得到当前的账号
            String username = userDetails.getUsername();
            //当前用户可以访问的资源路径
            List<SysRequestPath> paths = sysRequestPathService.getPathByUName(username);
            boolean match = paths.stream().anyMatch(sysRequestPath -> antPathMatcher.match(sysRequestPath.getUrl(), url));
            return match;
        }
        return false;
    }
}
